package com.kws.merchant.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.OrderPo;
import com.kws.merchant.domain.vo.*;
import com.kws.merchant.mapper.OrderMapper;
import com.kws.merchant.service.*;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单(Order)表服务实现类
 *
 * @author yxy
 * @since 2024-10-22 17:21:08
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private OperationWorkOrderService operationWorkOrderService;
    @Autowired
    private OperationPollingService operationPollingService;
    @Autowired
    private OperationMaintainService operationMaintainService;
    @Autowired
    @Lazy
    private MerchantService merchantService;
    @Autowired
    @Lazy
    private ItemService itemService;

    //    @Value("${otherHttp.url}")
    private static String wdwUr = "http://114.132.57.74/kwh-ems";

    /**
     * 分页查询列表
     *
     * @param order
     * @return
     */
    @Override
    public Page<Order> pageList(OrderPo order) {
        Page<Order> page = new Page<>(order.getPageSize(), order.getTotalPage());
        LambdaQueryWrapper<Order> queryWrapper = Wrappers.<Order>lambdaQuery();
        String orderNo = order.getOrderNo();//订单编号
        String deviceId = order.getDeviceId();//设备名称
        Long companyId = AuthUtil.getLoginUser().getCompanyId();//商家
        String status = order.getStatus();//状态
        queryWrapper.eq(Order::getMerchantId, companyId);
        if (!StringUtils.isEmpty(orderNo)) {
            queryWrapper.like(Order::getOrderNo, orderNo);
        }
        if (!StringUtils.isEmpty(deviceId)) {
            queryWrapper.like(Order::getGoodsId, deviceId);
        }
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.like(Order::getStatus, status);
        }
        if (companyId != null) {
            queryWrapper.eq(Order::getMerchantId, companyId);
        }
        return this.page(page, queryWrapper);
    }

    /**
     * 待付款、发货、售后统计
     *
     * @return
     */
    @Override
    public OrderStatistics statistics() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        //查询商机订单，不包含已完成订单
        List<Order> list = this.list(Wrappers.<Order>lambdaQuery().eq(Order::getMerchantId, companyId).ne(Order::getStatus, 3));
        OrderStatistics orderStatistics = new OrderStatistics();
        AtomicInteger payment = new AtomicInteger(0);//待付款
        AtomicInteger shipments = new AtomicInteger(0);//待发货
        AtomicInteger afterSales = new AtomicInteger(0);//待售后
        list.forEach(x -> {
            switch (x.getStatus()) {
                case 0:
                    payment.getAndIncrement();
                    break;
                case 1:
                    shipments.getAndIncrement();
                    break;
                case 2:
                    afterSales.getAndIncrement();
                    break;
            }

        });
        //查询商家所有工单
        List<OperationWorkOrder> workOrders = operationWorkOrderService.listByMerchant(companyId);
        //查询商家所有巡检
        List<OperationPolling> operationPollings = operationPollingService.listByMerchant(companyId);
        orderStatistics.setUnpaid(payment.get());
        orderStatistics.setUnAfterSale(afterSales.get());
        orderStatistics.setWorkOrder(workOrders.size());
        orderStatistics.setUnShipments(shipments.get());
        orderStatistics.setPolling(operationPollings.size());
        return orderStatistics;
    }

    /**
     * 新增订单
     *
     * @param order
     * @return
     */
    @Override
    public Object addOrder(Order order) {
        return this.save(order);
    }

    /**
     * 根据日期查询当前商家订单
     *
     * @param today
     * @return
     */
    @Override
    public List<Order> listByMerChantByTime(Long merchantId, String today) {
        return this.list(Wrappers.<Order>lambdaQuery().eq(Order::getMerchantId, merchantId).like(Order::getCreateTime, today));
    }

    /**
     * 根据时间查询订单数量
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double listOrderByTime(Long userId, String time) {
        return this.baseMapper.listOrderByTime(userId, time);
    }

    /**
     * 根据时间查询支付买家数
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double listOrderPayByTime(Long userId, String time) {
        return this.baseMapper.listOrderPayByTime(userId, time);
    }


    /**
     * 统计近30天内支付金额排行
     *
     * @param companyId
     * @param date
     * @param beforeDate
     * @return
     */
    @Override
    public List<OrderRankVo> userPayRanking(Long companyId, String date, String beforeDate, Integer type) {
        return this.baseMapper.payRanking(companyId, date, beforeDate, type);
    }


    /**
     * 根据类型时间查询支付金额
     *
     * @param companyId
     * @param time
     * @param type
     * @return
     */
    @Override
    public int merchantPayMoneyByTimeByType(Long companyId, String time, Integer type) {
        return this.baseMapper.merchantPayMoneyByTimeByType(companyId, time, time);
    }

    /**
     * 根据类型时间查询支付买家数
     *
     * @param companyId
     * @param time
     * @param type
     * @return
     */
    @Override
    public int listOrderPayByTimeByType(Long companyId, String time, Integer type) {
        return this.baseMapper.listOrderPayByTimeByType(companyId, time, type);
    }

    /**
     * 根据类型时间查询支付订单数
     *
     * @param companyId
     * @param time
     * @param type
     * @return
     */
    @Override
    public int payOrderNumByType(Long companyId, String time, Integer type) {
        return this.baseMapper.payOrderNumByType(companyId, time, type);
    }

    @Override
    public List<Order> detailByOrderNo(String orderNo) {
        return this.list(Wrappers.<Order>lambdaQuery().eq(Order::getOrderNo, orderNo).in(Order::getStatus, "1,2,3,4,6"));
    }

    /**
     * 支付金额
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double merchantPayMoneyByTime(Long userId, String time) {
        return this.baseMapper.merchantPayMoneyByTime(userId, time);
    }

    /**
     * 总的支付金额
     *
     * @param userId
     * @return
     */
    @Override
    public Double countPayNum(Long userId) {
        return this.baseMapper.countPayNum(userId);
    }

    /**
     * 总订单数
     *
     * @param userId
     * @return
     */
    @Override
    public Double countOrder(Long userId) {
        return this.baseMapper.countOrder(userId);
    }

    /**
     * 总支付买家数
     *
     * @param userId
     * @return
     */
    @Override
    public Double countPayOrder(Long userId) {
        return this.baseMapper.countPayOrder(userId);
    }

    /**
     * 根据年月查询支付金额
     *
     * @param companyId
     * @param type
     * @return
     */
    @Override
    public Double countPayByYearAndMonth(Long companyId, Integer year, Integer month, Integer type) {
        return this.baseMapper.countPayByYearAndMonth(companyId, year, month, type);
    }

    /**
     * 根据年月查询退款金额
     *
     * @param companyId
     * @param type
     * @return
     */
    @Override
    public Double refundPayByYearAndMonth(Long companyId, Integer year, Integer month, Integer type) {
        return this.baseMapper.refundPayByYearAndMonth(companyId, year, month, type);
    }

    /**
     * 根据sql查询支付金额
     *
     * @param companyId
     * @param type
     * @param sql
     * @return
     */
    @Override
    public Double countPayBySql(Long companyId, Integer type, String sql) {
        if (type == null) {
            return this.baseMapper.countPayBySqlType(companyId, sql);

        } else {

            return this.baseMapper.countPayBySql(companyId, type, sql);
        }
    }

    /**
     * 根据sql查询退款金额
     *
     * @param companyId
     * @param type
     * @param sql
     * @return
     */
    @Override
    public Double refundPayBySql(Long companyId, Integer type, String sql) {
        return this.baseMapper.refundPayBySql(companyId, type, sql);
    }

    /**
     * 支付买家数
     *
     * @param companyId
     * @param type
     * @param sql
     * @return
     */
    @Override
    public Double countPayPeopleBySql(Long companyId, Integer type, String sql) {
        return this.baseMapper.countPayPeopleBySql(companyId, type, sql);
    }

    /**
     * 支付订单数
     *
     * @param companyId
     * @param type
     * @param sql
     * @return
     */
    @Override
    public Double countPayOrderBySql(Long companyId, Integer type, String sql) {
        return this.baseMapper.countPayOrderBySql(companyId, type, sql);
    }

    /**
     * 当前商家排行
     *
     * @param companyId
     * @param date
     * @param beforeDate
     * @param type
     * @return
     */
    @Override
    public Integer merchantPayRankingByOne(Long companyId, String date, String beforeDate, Integer type) {
        return this.baseMapper.merchantPayRankingByOne(companyId, date, beforeDate, type);
    }

    /**
     * 商家订单列表
     *
     * @return
     */
    @Override
    public List<Order> listByMerchant() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.list(Wrappers.<Order>lambdaQuery().eq(Order::getMerchantId, companyId));
    }

    /**
     * 新增物流编号和设备编号-用户商家填写物流编号时
     *
     * @param logisticsPo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addLogistic(LogisticsPo logisticsPo) {
        Long orderId = logisticsPo.getOrderId();
        String deviceNo = logisticsPo.getDeviceNo();//设备编号
        Order order = this.getById(orderId);
        if (ObjectUtils.isEmpty(order)) {
            throw new RuntimeException("没有该订单信息");
        }
        order.setTrackingNumber(logisticsPo.getTrackingNumber());//单号
        order.setSendAddress(logisticsPo.getSendAddr());//发货地址
        String expressCompany = logisticsPo.getExpressCompany();//快递公司
        //如果发货地址为空，则默认为用户注册地址
        if (StringUtils.isEmpty(expressCompany)) {
            Merchant merchant = merchantService.getById(order.getMerchantId());
            expressCompany = merchant.getCompanyAddress();
        }
        order.setExpressCompany(expressCompany);//快递公司
        //调用第三方注册设备接口
        Long itemId = order.getItemId();//项目
        String itemName = "";
        if (itemId != null) {
            Item item = itemService.getById(itemId);
            if (!ObjectUtils.isEmpty(item)) {
                itemName = item.getItemName();
            }
        }
        Long goodsId = order.getGoodsId();
        String goodsName = order.getGoodsName();
        HashMap<String, Object> map = new HashMap<>();
        map.put("cid", itemId == null ? "" : itemId);//项目id
        map.put("name", itemName);//项目名称
        map.put("sid", deviceNo);//设备编号
        map.put("product_id", goodsId);//产品id
        map.put("product_name", goodsName);//产品名称
        String post = HttpUtil.post(wdwUr + "/micro-grid/third-party/config/third-register-monitor", map);
        JSONObject jsonObject = JSON.parseObject(post, JSONObject.class);
        String data = jsonObject.getOrDefault("data", "").toString();
        if (StringUtils.isEmpty(data)) {
            throw new RuntimeException("注册设备调用失败");
        }
        JSONObject dataObj = JSON.parseObject(data, JSONObject.class);
        String success = dataObj.getOrDefault("success", "0").toString();
        if ("0".equals(success)) {
            throw new RuntimeException("注册设备调用失败");
        }
        return this.updateById(order);
    }

    /**
     * 统计订单销售数量
     *
     * @param id
     * @return
     */
    @Override
    public Integer countByGoodsId(Long id) {
        return this.baseMapper.countByGoodsId(id);
    }

    /**
     * 按项目类型统计销售额
     *
     * @param companyId
     * @param sql
     */
    @Override
    public List<MicrogridSale> countPayBySqlGroupByProjectType(Long companyId, String sql) {
        return this.baseMapper.countPayBySqlGroupByProjectType(companyId, sql);
    }

    /**
     * 根据类型查询对应记录
     *
     * @param companyId
     * @param workType
     * @param sql
     * @return
     */
    @Override
    public Double countWorkTypeBySql(Long companyId, Integer workType, String sql) {
        //0工单 1巡检 2报修 3抢修
        Double num = 0.0;
        switch (workType) {
            case 0:
                num = operationWorkOrderService.countWorkTypeBySql(companyId, sql);
                break;
            case 1:
                num = operationPollingService.countWorkTypeBySql(companyId, sql);
                break;
            case 2:
            case 3:
                if (workType == 2) {
                    num = operationMaintainService.countWorkTypeBySql(companyId, 0, sql);
                } else {

                    num = operationMaintainService.countWorkTypeBySql(companyId, 1, sql);
                }
                break;
        }
        return num;
    }

    /**
     * 微电网-销售量、销售额统计
     * @param sql
     * @return
     */
    @Override
    public ItemStatisticsVo itemStatistics(Long companyId,String sql) {
        return orderMapper.itemStatistics(companyId,sql);
    }

    /**
     * 统计总的金额
     * @param companyId
     * @param sql
     * @return
     */
    @Override
    public Integer countOrderPrice(Long companyId, String sql) {
        return orderMapper.countOrderPrice(companyId,sql);
    }

    /**
     * 按订单类型统计销售额
     * @param companyId
     * @param sql
     * @return
     */
    @Override
    public List<MicrogridOrder> countPayBySqlGroupByOrderStatus(Long companyId, String sql) {
        return orderMapper.countPayBySqlGroupByOrderStatus(companyId,sql);
    }


}
